#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  GPS2Speedmp4.py
#
#  Copyright 2018 Martin Schöön <martin.schoon@ieee.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
# This example uses a MovieWriter directly to grab individual frames and
# write them to a file. This avoids any event loop integration, but has
# the advantage of working with even the Agg backend. This is not
# recommended for use in an interactive setting.
#
''' This program reads a GPS data file created by SONY action cameras
and produces a move file on mp4-format. The movie shows a speed bar and
numeric speed information in knots. The frame rate is 1 frame per second.

This program is run from comman line as

GPS2Speedmp4.py infilename outfilename
'''

import sys
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as manimation

import ReadNMEA as rn


# Read mandatory file names
#

try:
    infilename = sys.argv[1]
    outfilename = sys.argv[2]
except:
    print(usage); sys.exit(1)


# Read and convert data from GPS data file from camera
#

lat, lon, v = rn.ReadGPSData(infilename)  # Acquire data

# Set up video export
#

FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title='Speedo', artist='Martin Schoeoen',
                comment='Video overlay')
writer = FFMpegWriter(fps=1, codec='png', metadata=metadata)

# Prepare/format speed graphics
#
n_groups = 4
v_g = (0, 0, 0, 0)
index = np.arange(n_groups)
bar_width = 0.25
opacity = 1.0

rect_labels = []

plt.style.use('dark_background')

fig = plt.figure()
plt.axis('off')
fig.patch.set_alpha(0.00)

plt.xlim(0, 5)
plt.ylim(0, 25)

# Moving speedo bar and read-out
#

v0 = 0.0

with writer.saving(fig, outfilename, 100):  # last number: scale in %
    for i in range(lat.size):
        v0 = v[i]
        v_g = (v0, 0, 0, 0)
        rects = plt.bar(index, v_g, bar_width, alpha=opacity, color='orange')
        for rect in rects:
            height = rect.get_height()
            rankStr = str(height)
            yloc = height
            clr = 'orange'
            align = 'left'
            xloc = rect.get_width() + 0.1
            label = plt.text(xloc, yloc, rankStr, horizontalalignment=align,
                             verticalalignment='center', color=clr,
                             weight='bold', fontsize=24, clip_on=False)

        rect_labels.append(label)

        plt.ylim(0, 25)
        plt.axis('off')
        writer.grab_frame()
        plt.cla()  # This axes clearing is needed as plt.hold is depreciated.
